package com.app.drops_water.widget

import android.appwidget.AppWidgetManager
import android.content.Context
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.compose.runtime.rememberCoroutineScope
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.glance.GlanceId
import androidx.glance.appwidget.GlanceAppWidget
import androidx.glance.appwidget.GlanceAppWidgetManager
import androidx.glance.appwidget.GlanceAppWidgetReceiver
import androidx.glance.appwidget.provideContent
import androidx.glance.appwidget.state.updateAppWidgetState
import androidx.glance.appwidget.updateAll
import androidx.glance.currentState
import com.app.drops_water.data.longToStringDate
import com.app.drops_water.data.preferences.DefaultPreferences
import com.app.drops_water.data.preferences.Preferences
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.Timer
import java.util.TimerTask
import com.app.drops_water.data.preferences.Preferences as AppPreferences

object TrackerWidget : GlanceAppWidget() {

    const val KEY_WIDGET_COUNT = "count"

    val countKey = intPreferencesKey(KEY_WIDGET_COUNT)

    val msKey = longPreferencesKey("TrackerWidget.ms")

    private var timer: Timer? = null
    private var ms = 0L

    private fun startAutoRefresh(ctx: Context) {
        timer?.cancel()
        timer = null
        timer = Timer()
        timer?.schedule(object : TimerTask() {
            override fun run() {
                ms = System.currentTimeMillis()
                refreshWidget(ctx)
                Log.d("小组件", "ms:${ms.longToStringDate()}")
            }

        }, 0, 1000)
    }

    fun refreshWidget(ctx: Context) {
        CoroutineScope(Dispatchers.IO).launch {
            GlanceAppWidgetManager(ctx)
                .getGlanceIds(TrackerWidget::class.java).firstOrNull()?.let { glanceId ->
                    updateAppWidgetState(ctx, glanceId) { prefs ->
                        prefs[msKey] = System.currentTimeMillis()
                    }
                    TrackerWidget.update(ctx, glanceId)
                }
        }
    }

    override suspend fun onDelete(context: Context, glanceId: GlanceId) {
        super.onDelete(context, glanceId)
        timer?.cancel()
        timer = null
    }

    override suspend fun provideGlance(context: Context, id: GlanceId) {

        val preferences = DefaultPreferences(
            context.getSharedPreferences(
                AppPreferences.PREF_NAME,
                ComponentActivity.MODE_PRIVATE
            )
        )



        provideContent {

            timer ?: run { startAutoRefresh(context) }

            val count = currentState(key = countKey) ?: preferences.getCount()
            val ms = currentState(key = msKey) ?: preferences.getMs()

            if (preferences.isSetUp()) {

                val localGoal = preferences.getGoal()
                val countPercent = count * 10 / localGoal

                context.WidgetContent(count = count, countPercent = countPercent, timeStr = ms.longToStringDate())

            } else {
                context.WidgetEmptyContent()
            }
        }
    }

}


class CounterWidgetReceiver : GlanceAppWidgetReceiver() {

    override val glanceAppWidget: GlanceAppWidget
        get() = TrackerWidget

    override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
        super.onUpdate(context, appWidgetManager, appWidgetIds)
        Log.d("小组件", " CounterWidgetReceiver :onUpdate ")
    }

}


